
echo "~~~~~~~~~~~~~~~~开始执行脚本~~~~~~~~~~~~~~~~"
#开始时间
beginTime=`date +%s`
DATE=`date '+%Y-%m-%d-%T'`

# 当前用户是刘张鹏
pgyerUKey=$(cat package/pgyerUKey)  # 这里替换蒲公英ukey
echo -e "\033[31m pgyerUKey: ${pgyerUKey} \033[0m"
pgyerApiKey=$(cat package/pgyerApiKey) # 这里替换蒲公英apiKey
echo -e "\033[31m pgyerApiKey: ${pgyerApiKey} \033[0m"

# target_name 一般是工程的名字
target_name="TextToImg"
#配置变量
target_dir="../archive"/${target_name}_${DATE}
target_plist="package/ExportOptions.plist"

# 当前目录
currunt_dir=$(pwd)

# 项目启动所在的路径
projectFile_name=${currunt_dir}/${target_name}/${target_name}.xcodeproj
projectFile_name_pod=${currunt_dir}/${target_name}.xcworkspace

#编译路径
buildPath=${target_dir}/build_ipa
#archivePath
archivePath=${target_dir}/${target_name}.xcarchive 

# Xcode 构建
echo "~~~~~~~~~~~~~~~~开始构建~~~~~~~~~~~~~~~~~~~"
echo ${projectFile_name_pod}
# 使用pod
xcodebuild archive -workspace ${projectFile_name_pod} -scheme ${target_name} -configuration Release -archivePath ${archivePath}

# 不使用pod
#xcodebuild archive -project ${projectFile_name} -scheme ${target_name} -configuration Release -archivePath ${archivePath}

echo "~~~~~~~~~~~~~~~~检查是否构建成功~~~~~~~~~~~~~~~~~~~"
# xcarchive 实际是一个文件夹不是一个文件所以使用 -d 判断
if [ -d "$archivePath" ]
	then
		echo "构建成功......"
		endTime=`date +%s`
		ArchiveTime="构建时间$[ endTime - beginTime ]秒"
		echo "$ArchiveTime"
	else
		echo "构建失败......"
		rm -rf $target_dir
		exit -1
fi


echo "~~~~~~~~~~~~~~~~导出ipa~~~~~~~~~~~~~~~~~~~"
beginTime=`date +%s`

xcodebuild -exportArchive -archivePath ${archivePath} -exportPath ${buildPath} -exportOptionsPlist ${target_plist}

echo "~~~~~~~~~~~~~~~~检查是否成功导出ipa~~~~~~~~~~~~~~~~~~~"

ipaPath=${buildPath}/${target_name}.ipa
if [ -f "$ipaPath" ]
	then
		echo "导出ipa成功......"
		# 结束时间
		endTime=`date +%s`
		ExportTime="导出ipa时间$[ endTime - beginTime ]秒"
		echo "$ExportTime"

        echo -e "\033[31m ipa path : ${ipaPath}\033[0m"

        #获取git最新提交
        commit_name=$(git log --pretty=format:"%s" -1)
        echo -e "\033[31m 更新内容：${commit_name} \033[0m"

        echo -e "\033[31m 开始上传 \033[0m"
        #通过api上传到蒲公英当中

        RESULT=$(curl -F "file=@$ipaPath" -F "uKey=$pgyerUKey" -F "_api_key=$pgyerApiKey" -F "updateDescription=${commit_name}" http://www.pgyer.com/apiv1/app/upload)

        echo -e "\033[31m $RESULT \033[0m"

        if [ ! -n "$RESULT" ] ;then
            echo -e "\033[31m 上传失败 \033[0m"
            exit -1
        else
            echo -e "\033[31m 完成上传 \033[0m"
        fi
	else
		echo "导出ipa失败......"
		rm -rf $buildPath
		exit -1
fi



exit 1












